package com.marketapp.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.marketapp.domain.Sector;
import com.marketapp.helper.ServiceException;
import com.marketapp.service.ISectorService;
import com.marketapp.validators.SectorValidator;

@Controller
@RequestMapping(value="/admin_add_sector")
public class AdminAddSectorController {
	
	@Autowired
	ISectorService sectorService;
	
	@Autowired
	SectorValidator validator;

	public ISectorService getSectorService() {
		return sectorService;
	}

	public void setSectorService(ISectorService sectorService) {
		this.sectorService = sectorService;
	}
	
	@RequestMapping(method=RequestMethod.GET)
	public void setUpForm(Model model){
		Sector sector = new Sector();
		model.addAttribute("sector",sector);
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public String submitForm(@ModelAttribute(value="sector")Sector sector,
			BindingResult result, Model model) throws ServiceException{
		validator.validate(sector, result);
		if(result.hasErrors()){
			model.addAttribute("successFlag", false);
			return "admin_add_sector";
		}else{
			sectorService.saveSector(sector);
			model.addAttribute("successFlag", true);
			return "admin_add_sector";
		}
	}
}
